<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Image as Base64</title>
    <script>
        function downloadImage() {
            // 获取文件名
            const fileName = document.getElementById('fileName').value;

            // 创建 XMLHttpRequest 对象
            var xhr = new XMLHttpRequest();
            xhr.open('GET', `http://127.0.0.1:8004/fileBase64Down/download?fileName=${encodeURIComponent(fileName)}`, true);
            xhr.responseType = 'json'; // 设置响应类型为 JSON

            // 处理响应
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    // 解析返回的 JSON 数据
                    var data = xhr.response;
                    if (data.error) {
                        // 处理错误
                        alert(data.error);
                        return;
                    }
                    // 将 Base64 转换为 Blob 对象
                    const byteCharacters = atob(data.base64);
                    const byteNumbers = new Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    const blob = new Blob([byteArray], {type: 'image/png'}); // 根据实际图片类型修改 MIME 类型

                    // 创建一个链接元素用于下载
                    const link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = data.fileName;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } else {
                    // 处理其他错误
                    alert('An error occurred while downloading the image.');
                }
            };

            // 发送请求
            xhr.send();
        }
    </script>
</head>
<body>
<input type="text" id="fileName" placeholder="Enter file name">
<button onclick="downloadImage()">Download Image</button>
</body>
</html>
